import 'package:flutter/material.dart';
import 'package:flutter_basic_learning/widgets/CommonHeader.dart';

import '../../utils/KeepAliveWrap.dart';
import 'HomePage.dart';
import 'MinePage.dart';

class BottomNavigationBarPage extends StatefulWidget {
  const BottomNavigationBarPage({super.key});

  @override
  State<BottomNavigationBarPage> createState() =>
      _BottomNavigationBarPageState();
}

class _BottomNavigationBarPageState extends State<BottomNavigationBarPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(length: barList.length, vsync: this);

    //监听_tabController
    //因为动画tab动画开始和结束都会触发监听，所以加个判断,避免重复执行
    _tabController.addListener(() {
      if (_tabController.animation!.value == _tabController.index) {
        print('当前选中的index: ${_tabController.index}');
      }
    });
  }

  int _currIndex = 0;
  List<BottomNavigationBarItem> barList = [
    const BottomNavigationBarItem(
      icon: Icon(Icons.home_filled),
      label: '首页',
    ),
    const BottomNavigationBarItem(icon: Icon(Icons.hotel_class), label: '热点'),
    const BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的')
  ];

  List<Widget> pageList = [
    const KeepAliveWrap(child: HomePage()),
    // const KeepAliveWrap(child: HotPage(arguments: {'title': '我的标题'})),
    const KeepAliveWrap(child: MinePage()),
  ];

  BottomNavigationBar bottomNavigationBar() {
    BottomNavigationBar bottomNavigationBar = BottomNavigationBar(
      iconSize: 30, //设置默认icon图标大小
      fixedColor: Colors.orange, //选中的菜单样式
      unselectedItemColor: Colors.grey, //危险中的菜单项样式
      currentIndex: _currIndex, //当前选中的菜单索引,默认为0
      type: BottomNavigationBarType.fixed, //底部菜单超过3个，需要配置此参数，否则显示异常
      items: barList, //菜单项列表
      onTap: (index) {
        //点击菜单项的回调，返回点击的索引
        setState(() {
          _currIndex = index;
        });
      },
    );
    return bottomNavigationBar;
  }

  List<Tab> tabs = const [
    Tab(icon: Icon(Icons.home_filled), text: '首页'),
    Tab(icon: Icon(Icons.hotel_class), text: '热点'),
    Tab(icon: Icon(Icons.person), text: '我的'),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //构建标题栏
      appBar: const CommonHeader(title: 'BottomNavigationBarPage'),
      //内容区域
      body: TabBarView(
        children: pageList,
        controller: _tabController,
      ),
      //底部导航栏
      bottomNavigationBar: TabBar(
        tabs: tabs,
        controller: _tabController,
      ),
      // bottomNavigationBar: bottomNavigationBar(),
    );
  }
}
